<template>
    <view class="page_main">
        <HeaderBar title="申请退款"></HeaderBar>
        <view class="container">
            <!-- 商品信息 -->
            <view class="goods">
                <img class="img" :src="productInfo.headImgUrl" alt="">
                <view class="goods_info">
                    <view class="info">
                        <view>{{ productInfo.name }}</view>
                        <view>￥{{(productInfo?.adultPrice * productInfo?.adultNum 
                            + productInfo?.childrenPrice * productInfo?.childrenNum)
                            .toFixed(2)}}</view>    
                    </view>
                    <view class="count">
                        <view><text v-if="productInfo?.adultNum">成人{{productInfo?.adultNum}}人</text><text v-if="productInfo?.adultNum">儿童{{productInfo?.adultNum}}人</text></view>
                        <view>×{{ productInfo.quantity }}</view>   
                    </view>
                    <view class="memo">{{ productInfo.desc }}</view>
                    <view class="date"> 出发日期：{{productInfo.useDate}}</view>
                    <view class="num_input">
                        <wd-input-number v-model="value" :max="productInfo.quantity" @change="numHandleChange" />
                    </view>            
                </view>  
            </view> 
            <!-- 出行人信息 -->
            <wd-collapse viewmore v-model="collapseRoot" @change="handleChange" :line-num="3"  use-more-slot custom-more-slot-class="more-slot">
                <view class="title">出行人信息（<text v-if="adultCount">{{ adultCount }}成人</text><text v-if="childrenCount">{{ childrenCount }}儿童</text>）</view>  
                <view class="list" v-if="travelers.adults.length">
                    <view class="label">成人</view> 
                    <view class="info">
                        <view class="item" v-for="(item ,index) in travelers.adults" :key="index">
                            <view class="text">
                                姓名：{{ item.name }}<text class="tag">{{ refundStatusMap[item.refundStatus] }}</text>
                            </view>
                            <view class="text">
                                身份证号：{{ item.showFull ? item.idCard : maskIdCard(item.idCard) }}
                                <uni-icons :type="item.showFull?'eye':'eye-slash'" size="18" @click="toggleShowIdCard(item)"/>
                            </view>
                            <label class="radio"><radio :value="item.id" :disabled="[0, 1].includes(item.refundStatus)" :checked="item.selected" @click="handleRadioClick(item, $event)" /></label>
                        </view>
                    </view>
                </view>
                <view class="list" v-if="travelers.children.length">
                    <view class="label">儿童</view>
                    <view class="info">
                        <view class="item" v-for="(item ,index) in travelers.children" :key="index">
                            <view class="text">
                                姓名：{{ item.name }}<text class="tag">{{ refundStatusMap[item.refundStatus] }}</text>
                            </view>
                            <view class="text">
                                身份证号：{{ item.showFull ? item.idCard : maskIdCard(item.idCard) }}
                                <uni-icons :type="item.showFull?'eye':'eye-slash'" size="18" @click="toggleShowIdCard(item)"/>
                            </view>
                            <label class="radio"><radio :value="item.id" :disabled="[0, 1].includes(item.refundStatus)" :checked="item.selected" @click="handleRadioClick(item, $event)" /></label>
                        </view>
                    </view>
                </view>
                <template class="more" #more>
                    <view class="more_i" v-if="!collapseRoot">查看更多<uni-icons type="down" size="18"></uni-icons></view>
                    <view class="more_i" v-else>点击收起<uni-icons type="up" size="18"></uni-icons></view>
                </template>
            </wd-collapse>
            <!-- 退款表单 -->
            <view class="form">
                <view class="form_head">
                    <view class="title">退款金额</view>
                    <view class="price">￥<text>{{refundAmount}}</text></view>    
                </view>
                <view class="tip">1-3 个工作日退还至原支付方，以实际退款金额为准</view>
                <view class="cell">
                    <view class="title">退款原因<text style="color: #AA5413;">*</text></view>
                    <view class="reason">
                        {{reason}}
                    </view>
                    <view class="icons" @click="show = true">
                        <text v-if="!reason.value">请选择</text>
                        <uni-icons type="right" size="14"></uni-icons> 
                    </view>
                </view>
                <view class="other">
                    <view class="title">其他原因</view>
                    <wd-textarea v-model="otherReason" placeholder="补充退款原因详情，有助于平台更好的为你服务" />  
                    
                </view>  
            </view>
        </view>
        <!-- 退款按钮 -->
        <view class="btns">
            <view class="b_price">
                退款金额
                <view class="num">
                    ￥<text>{{refundAmount}}</text>
                </view>  
            </view>
            <button class="btn" @click="handleSubmit" :disabled="isSubmitting || refundAmount <= 0">{{ isSubmitting ? '提交中...' : '提交' }}</button>   
        </view>
        <!-- 退款原因弹窗 -->
        <wd-action-sheet v-model="show" title="退款原因" @close="close">
            <view class="sheet_content" style="padding: 15px 15px 150px 15px;">
                <wd-radio-group v-model="reasonValue" cell @change="changeRadio">
                    <wd-radio
                        v-for="reason in reasonList"
                        :key="reason.value"
                        :value="reason.value"
                    >
                        {{ reason.label }}
                    </wd-radio>
                </wd-radio-group>
                <button class="btn_con" @click="handconfirm">确认</button>
            </view>
        </wd-action-sheet>
    </view>
</template>

<script lang="ts" setup>
import {ref ,computed, onMounted} from "vue";
import HeaderBar from "@/components/HeaderBar/index.vue";
import { onLoad } from '@dcloudio/uni-app';
import {requestRefund } from "@/premiumRouteSubPack/api/index"

const value =ref(0)
const collapseRoot = ref()  //人员信息展开状态
interface ProductInfo {
  id: string;
  name: string;
  desc: string;
  quantity: number;
  adultPrice: number;
  childrenPrice: number;
  adultNum: number;
  childrenNum: number;
  totalAmount: number;
  useDate: string;
  headImgUrl: string;
}

interface Traveler {
  id?: string;
  name: string;
  idCard: string;
  refundStatus?: number;
}

const refundStatusMap = {
  0: '退款成功',
  1: '退款中'
};
const reasonList = [
    { value: 0, label: '计划有变没时间消费' },
    { value: 1, label: '买多了/买错了' },
    { value: 2, label: '担心安全问题(天气等)' },
    { value: 3, label: '后悔了，不想要了' },
    { value: 4, label: '误以为是外卖' },
    { value: 5, label: '没看清使用规则，要用时才发现限制多' },
]
const productInfo = ref<ProductInfo>({
  id: '',
  name: '',
  desc: '',
  quantity: 0,
  adultPrice: 0,
  childrenPrice: 0,
  adultNum: 0,
  childrenNum: 0,
  totalAmount: 0,
  useDate: '',
  headImgUrl: '',
});

const travelers = ref<{
  adults: Traveler[];
  children: Traveler[];
}>({
  adults: [],
  children: []
});
const reason = ref('')
const otherReason = ref('')
const isSubmitting = ref(false);
onLoad((options) => {
  try {
    const data = JSON.parse(decodeURIComponent(options.data || '{}'));
    
    productInfo.value = {
      ...data.productInfo,
      totalAmount: Number(data.productInfo.totalAmount || 0)
    };

    travelers.value = {
      adults: data.travelers?.adults || [],
      children: data.travelers?.children || []
    };
  } catch (error) {
    uni.showToast({ title: '数据加载失败', icon: 'none' });
    uni.navigateBack();
  }
});
const adultCount = computed(() => travelers.value?.adults?.length || 0);
const childrenCount = computed(() => travelers.value?.children?.length || 0);
const show =ref(false)   //退款原因弹窗
const reasonValue =ref(0)   //退款原因
//改变数量
const numHandleChange =({value})=>{
    console.log('...',value);
    
}
const handleChange =()=>{
    console.log('展开面板11111');
    
}
const maskIdCard =(idCard)=> {
    if (!idCard) return '';
    return idCard.replace(/(?<=.{6}).(?=.{4})/g, '*');
}
const toggleShowIdCard =(item)=> {
    item.showFull= !item.showFull;
}
//人员列表选中状态
const handleRadioClick =(item)=> {
    if ([0, 1].includes(item.refundStatus)) return;
    item.selected = !item.selected; 
}
const refundAmount = computed(() => {
  const adultCount = travelers.value.adults
    .filter(item => item.selected && ![0, 1].includes(item.refundStatus))
    .length;
  
  const childrenCount = travelers.value.children
    .filter(item => item.selected && ![0, 1].includes(item.refundStatus))
    .length;

  return (
    (adultCount * productInfo.value.adultPrice) + 
    (childrenCount * productInfo.value.childrenPrice)
  );
});
//提交
const handleSubmit = async () => {
  try {
    // 验证必填字段
    if (!reason.value) {
      uni.showToast({ title: '请选择退款原因', icon: 'none' });
      return;
    }
    // 获取选中人员ID（排除不可退款状态）
    const selectedTravelerIds = [
      ...travelers.value.adults
        .filter(item => item.selected && ![0, 1].includes(item.refundStatus))
        .map(item => item.id),
      ...travelers.value.children
        .filter(item => item.selected && ![0, 1].includes(item.refundStatus))
        .map(item => item.id)
    ].filter(Boolean) as string[];   
    if (selectedTravelerIds.length === 0) {
      uni.showToast({ title: '请选择要退款的人员', icon: 'none' });
      return;
    }

    // 组装请求数据
    const params = {
        orderId: productInfo.value.id,
        refundAmount: refundAmount.value,
        refundMemo: `${reason.value}${reason.value && otherReason.value ? '；' : ''}${otherReason.value}`,
        travelersId: selectedTravelerIds
    };

    isSubmitting.value = true;
    
    // 调用退款接口（假设为submitRefund）
    const res = await requestRefund(params);
    
    if (res.code === 0) {
      uni.showToast({ title: '退款申请提交成功' });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      throw new Error(res.msg || '退款申请失败');
    }
  } catch (error) {
    console.error('退款提交失败:', error);
    uni.showToast({ 
      title: error.message || '提交失败，请稍后重试',
      icon: 'none'
    });
  } finally {
    isSubmitting.value = false;
  }
};
//选择退款原因
const changeRadio =(e)=>{
    console.log('退款原因',e);
    
}
//确认原因
const handconfirm =()=>{
    const selectedReason = reasonList.find(item => item.value === reasonValue.value);
    if (selectedReason) {
        reason.value = selectedReason.label; // 将选中的原因赋值给reason
    }
    show.value = false; // 关闭弹窗
}
const close =()=>{
    show.value=false
}
</script>

<style lang="scss" scoped>
.page_main{
    background: #eeefe7;
    .container{
        padding: 40rpx 28rpx 280rpx;
        .goods{
            padding: 44rpx 28rpx 40rpx;
            border-radius: 10rpx;
            margin-top: -10rpx;
            background: #fff;
            display: flex;
            align-items: center;
            .img{
                width: 125rpx;
                height: 125rpx;
                border-radius: 10rpx;
                margin-right: 27rpx;
            }
            .goods_info{
                flex: 1;
                position: relative;
                .info{
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    font-size: 25rpx;
                    font-weight: bold;
                    color: #2b2b24;
                    margin-bottom: 15rpx;
                }
                .count{
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    font-size: 22rpx;
                    color: #777777;
                }
                .memo{
                    font-size: 22rpx;
                    color: #777777;
                    width: 300rpx;
                    white-space: nowrap; 
                    overflow: hidden;  
                    text-overflow: ellipsis;
                }
                .date{
                    font-size: 22rpx;
                    color: #777777;
                }
                .num_input{
                    position: absolute;
                    right: 0;
                    bottom: 0;
                }
            }
        }
        :deep(.wd-collapse){
            margin-top: 27rpx;
            border-radius: 10rpx;
            .title{
                font-size: 29rpx;
                font-weight: bold;
            }
            .list{
                position: relative;
                padding-left: 80rpx;
                margin-top: 42rpx;
                .label{
                    position: absolute;
                    left: 0;
                    top:0;
                    font-size: 29rpx;
                    font-weight: bold;
                }
                .info{
                    font-size: 25rpx;
                    .item{
                        margin-top: 35rpx;
                        position: relative;
                        .text{
                            margin-top: 10rpx;
                            .tag{
                                padding: 1rpx 8rpx;
                                background: #EFEFED;
                                border-radius: 7rpx;
                                color: #1B9C61;
                                margin-left: 20rpx;
                                font-size: 22rpx;
                            }
                        }
                        .radio{
                            position: absolute;
                            right: 0;
                            top:50%;
                            transform: translateY(-50%);
                        }
                    }
                }
            }
            .more-slot {
                border-top: 1px solid #c0c2b3;
                width: calc(750rpx - 28rpx*4);
                padding-top: 20rpx;
                margin-top: 20rpx;
                .more_i{
                    text-align: center;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: #2b2b24;
                }
            }
        }
        .form{
            padding: 60rpx 28rpx;
            margin-top: 27rpx;
            background: #fff;
            border-radius: 10rpx;
            .title{
                font-size: 29rpx;
                font-weight: bold;
            }
            .form_head{
                display: flex;
                align-items: center;
                justify-content: space-between;
                .price{
                    color: #AA5413;
                    text{
                        font-size: 29rpx;
                    }
                }
            }
            .tip{
                margin-top: 15rpx;
                font-size: 22rpx;
                color: #777;
            }
            .cell{
                margin-top: 20rpx;
                padding: 28rpx 0;
                border-top: 1rpx solid #c0c2b3;
                border-bottom: 1rpx solid #c0c2b3;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .reason{
                    font-size: 25rpx;
                    padding: 0 20rpx;
                    width: 300rpx;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                }
                .icons{
                    display: flex;
                    align-items: center;
                    font-size: 25rpx;
                }

            }
            .other{
                margin-top: 34rpx;
                :deep(.wd-textarea){
                    margin-top: 24rpx;
                    border: 1rpx solid #A7A7A7;
                    border-radius: 10rpx;
                    .wd-textarea__placeholder  {
                        font-size: 25rpx;
                    }
                }
            }

        }
    }
    .btns{
        width: 100%;
        padding: 40rpx 28rpx;
        padding-bottom: env(safe-area-inset-bottom);
        background: #EEF0DF;
        display: flex;
        align-items: center;
        justify-content: space-between;
        position: fixed;
        bottom: 0;
        left: 0;
        box-sizing: border-box;
        .b_price{
            display: flex;
            align-items: center;
            font-size: 29rpx;
            .num{
                color: #AA5413 ;
                text{
                    font-size: 40rpx;
                }
            }
        }
        .btn{
            width: 194rpx;
            height: 56rpx;
            line-height: 56rpx;
            color: #fff;
            background: #1B9C61;
            border-radius: 10rpx;
            margin: 0;
        }
    }
    .sheet_content{
        :deep(.wd-radio){
            border-top: 1px solid #e8e9e2;
        }
        .btn_con{
            margin-top: 52rpx;
            height: 69rpx;
            line-height: 69rpx;
            background: #1B9C61;
            border-radius: 10rpx;
            color: #fff;
            font-size: 29rpx;
        }
    }
}
</style>